<template>
  <el-main class="preview-area">
    <div class="preview-header">
      <h2>预览区域</h2>
      <div class="preview-actions">
        <el-button 
          type="primary" 
          size="small" 
          @click="handleAddInstance"
          :disabled="!currentComponent"
        >
          添加实例
        </el-button>
      </div>
    </div>
    
    <el-tabs type="border-card" class="preview-content">
      <el-tab-pane label="预览">
      <!-- 当前组件预览 -->
      <div v-if="currentComponent" class="current-preview">
        <h3>当前组件: {{ currentComponent.label }}</h3>
        <div class="component-preview">
          <component-renderer
            :component="currentComponent"
            :props="componentProps"
            :events="componentEvents"
            :slots="componentSlots"
            :children="componentChildren"
          />
        </div>
      </div>
      
      <!-- 组件实例列表 -->
      <div v-if="componentInstances.length > 0" class="instances-preview">
        <h3>组件实例列表</h3>
        <div 
          class="instances-container"
          :class="{
            'direction-row': previewLayout.direction === 'row',
            'direction-column': previewLayout.direction === 'column',
            'direction-grid': previewLayout.direction === 'grid'
          }"
          :style="{
            gap: `${previewLayout.gap}px`,
            gridTemplateColumns: previewLayout.direction === 'grid' ? 
              `repeat(${previewLayout.columns}, 1fr)` : 'auto'
          }"
        >
          <div 
            v-for="(instance, index) in componentInstances" 
            :key="index"
            class="instance-item"
            :class="[
              { 'active': editingInstanceIndex === index },
              instance.props.borderStyle ? `border-style-${instance.props.borderStyle}` : '',
              instance.props.borderRadius ? `border-radius-${instance.props.borderRadius}` : ''
            ]"
            :style="{
              borderWidth: instance.props.borderWidth || '1px',
              borderColor: instance.props.borderColor || '#ddd',
              transition: 'all 0.2s ease-in-out'
            }"
          >
            <div class="instance-actions">
              <el-button-group>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleEditInstance(index)"
                  :icon="Edit"
                />
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleRemoveInstance(index)"
                  :icon="Delete"
                />
              </el-button-group>
            </div>
            <component-renderer
              :component="instance.component"
              :props="instance.props"
              :events="instance.events"
              :slots="instance.slots"
              :children="instance.children"
            />
          </div>
        </div>
      </div>
      
      <!-- 预留区组件 -->
      <div v-if="reservedComponents.length > 0" class="reserved-preview">
        <h3>预留区组件</h3>
        <div class="instances-container">
          <div 
            v-for="(instance, index) in reservedComponents" 
            :key="'reserved-'+index"
            class="instance-item reserved-item"
            :class="[
              instance.props.borderStyle ? `border-style-${instance.props.borderStyle}` : '',
              instance.props.borderRadius ? `border-radius-${instance.props.borderRadius}` : ''
            ]"
            :style="{
              borderWidth: instance.props.borderWidth || '1px',
              borderColor: instance.props.borderColor || '#409eff',
              transition: 'all 0.2s ease-in-out'
            }"
          >
            <component-renderer
              :component="instance.component"
              :props="instance.props"
              :events="instance.events"
              :slots="instance.slots"
              :children="instance.children"
            />
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <el-empty 
        v-if="!currentComponent && componentInstances.length === 0 && reservedComponents.length === 0"
        description="请从左侧选择一个组件"
      />

    </el-tab-pane>
    <el-tab-pane label="代码">
      <div class="code-viewer">
        <el-alert 
          title="组件代码" 
          type="info" 
          :closable="false"
          show-icon
        >
          <template #default>
            <el-button 
              type="primary" 
              size="small" 
              :icon="DocumentCopy" 
              @click="copyCode"
            >
              复制代码
            </el-button>
          </template>
        </el-alert>
        <div class="code-container">
          <pre><code ref="codeRef" class="language-html">{{ generatedCode }}</code></pre>
        </div>
      </div>
    </el-tab-pane>
  </el-tabs>
  </el-main>
</template>

<script>
import { defineComponent, markRaw, computed, onMounted, ref } from 'vue'
import { Edit, Delete, DocumentCopy } from '@element-plus/icons-vue'
import ComponentRenderer from './ComponentRenderer.vue'
// 使用CDN引入的highlight.js
const hljs = window.hljs

export default defineComponent({
  name: 'PreviewArea',
  components: {
    ComponentRenderer
  },
  props: {
    currentComponent: {
      type: Object,
      default: null
    },
    componentProps: {
      type: Object,
      default: () => ({})
    },
    componentEvents: {
      type: Object,
      default: () => ({})
    },
    componentSlots: {
      type: Object,
      default: () => ({})
    },
    componentChildren: {
      type: Object,
      default: () => ({})
    },
    componentInstances: {
      type: Array,
      default: () => []
    },
    previewCount: {
      type: Number,
      default: 1
    },
    previewLayout: {
      type: Object,
      required: true
    },
    editingInstanceIndex: {
      type: Number,
      default: -1
    },
    reservedComponents: {
      type: Array,
      default: () => []
    }
  },
  emits: ['addInstance', 'editInstance', 'removeInstance', 'update:componentChildren'],
  setup(props, { emit }) {
    // 添加组件实例
    const handleAddInstance = () => {
      emit('addInstance')
    }

    // 子组件状态
    const componentChildren = ref({})
    
    // 添加子组件
    const handleAddChild = ({ childName, childComp }) => {
      if (!childComp) return
      
      const newChild = {
        name: childComp.name,
        props: {},
        slots: {},
        children: {}
      }
      
      // 初始化属性
      if (childComp.props) {
        Object.entries(childComp.props).forEach(([key, prop]) => {
          newChild.props[key] = prop.default !== undefined ? prop.default : ''
        })
      }
      
      // 初始化插槽
      if (childComp.slots) {
        Object.entries(childComp.slots).forEach(([key, slot]) => {
          newChild.slots[key] = {
            content: slot.default || '',
            isComponent: slot.isComponent || false,
            props: {}
          }
          
          if (slot.propsConfig) {
            Object.entries(slot.propsConfig).forEach(([propKey, propConfig]) => {
              newChild.slots[key].props[propKey] = propConfig.default !== undefined ? propConfig.default : ''
            })
          }
        })
      }
      
      // 更新组件子组件数据
      const newChildren = {...props.componentChildren}
      newChildren[childName] = newChild
      emit('update:componentChildren', newChildren)
    }
    
    // 编辑组件实例
    const handleEditInstance = (index) => {
      emit('editInstance', index)
    }
    
    // 移除组件实例
    const handleRemoveInstance = (index) => {
      emit('removeInstance', index)
    }
    
    const generatedCode = computed(() => {
      if (!props.currentComponent) return '// 请从左侧选择一个组件'
      
      const { name } = props.currentComponent
      let code = `<${name}`
      
      // 添加props
      Object.entries(props.componentProps).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          if (typeof value === 'string') {
            code += `\n  ${key}="${value}"`
          } else {
            code += `\n  :${key}="${JSON.stringify(value)}"`
          }
        }
      })
      
      // 添加events
      Object.entries(props.componentEvents).forEach(([key, value]) => {
        if (value) {
          code += `\n  @${key}="handle${key.charAt(0).toUpperCase() + key.slice(1)}"`
        }
      })
      
      // 添加slots
      const slots = Object.entries(props.componentSlots)
        .filter(([_, slot]) => slot.content)
        .map(([name, slot]) => {
          if (slot.isComponent) {
            return `\n  <template #${name}>\n    <${slot.content} ${Object.entries(slot.props)
              .map(([k, v]) => `:${k}="${JSON.stringify(v)}"`)
              .join(' ')} />\n  </template>`
          }
          return `\n  <template #${name}>${slot.content}</template>`
        })
        .join('')
      
      if (slots) {
        code += `>\n${slots}\n</${name}>`
      } else {
        code += ' />'
      }
      
      return code
    })

    // 复制代码
    const copyCode = () => {
      navigator.clipboard.writeText(generatedCode.value)
        .then(() => {
          ElMessage.success('代码已复制到剪贴板')
        })
        .catch(() => {
          ElMessage.error('复制失败')
        })
    }

    // 高亮代码
    const codeRef = ref(null)
    onMounted(() => {
      if (codeRef.value) {
        hljs.highlightElement(codeRef.value)
      }
    })

    return {
      handleAddInstance,
      handleEditInstance,
      handleRemoveInstance,
      Edit: markRaw(Edit),
      Delete: markRaw(Delete),
      DocumentCopy: markRaw(DocumentCopy),
      generatedCode,
      copyCode,
      codeRef
    }
  }
})
</script>

<style scoped>
.preview-area {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.preview-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.current-preview, .instances-preview {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 20px;
}

.current-preview h3, .instances-preview h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.component-preview {
  padding: 20px;
  border: 1px dashed #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.instances-container {
  display: flex;
}

.direction-row {
  flex-direction: row;
  flex-wrap: wrap;
}

.direction-column {
  flex-direction: column;
}

.direction-grid {
  display: grid;
}

.instance-item {
  position: relative;
  padding: 20px;
  border: 1px dashed #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.instance-item.active {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.instance-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 10;
}

.reserved-preview {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 20px;
  background-color: #f8f9fa;
}

.reserved-preview h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: #666;
}

.reserved-item {
  border: 1px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

/* 边框样式预设 */
.border-style-solid {
  border-style: solid !important;
}
.border-style-dashed {
  border-style: dashed !important;
}
.border-style-dotted {
  border-style: dotted !important;
}
.border-style-double {
  border-style: double !important;
}

/* 圆角预设 */
.border-radius-sm {
  border-radius: 2px !important;
}
.border-radius-md {
  border-radius: 4px !important;
}
.border-radius-lg {
  border-radius: 8px !important;
}
.border-radius-full {
  border-radius: 9999px !important;
}

/* 过渡效果 */
.instance-item,
.reserved-item {
  transition: all 0.2s ease-in-out;
}
.code-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.code-container {
  flex: 1;
  overflow: auto;
  margin-top: 10px;
  background: #f8f8f8;
  border-radius: 4px;
  padding: 12px;
}

.code-container pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.code-container code {
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.el-alert {
  margin-bottom: 10px;
}

.el-alert :deep(.el-alert__content) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

/* 高亮样式覆盖 */
.code-container :deep(.hljs) {
  background: #f8f8f8;
  padding: 0;
}

.code-container :deep(.hljs-tag),
.code-container :deep(.hljs-name),
.code-container :deep(.hljs-attr) {
  color: #2f6f9f;
}

.code-container :deep(.hljs-string) {
  color: #d44950;
}

.code-container :deep(.hljs-comment) {
  color: #999;
}
</style>